<?php

namespace App\Member\Controllers;

use App\Admin\Repositories\Withdrawal;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use App\Models\Withdrawal as WithdrawalModel;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Layout\Content;
use App\Admin\Metrics\Examples\NewDevices;
use App\Admin\Metrics\Examples\NewUsers;
use App\Admin\Metrics\Examples\TotalAdminUsers;
use App\Models\UserBalanceLog;
use App\Handlers\WithdrawalHandler;
use Carbon\Carbon;


class WithdrawalController extends BaseController
{


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Withdrawal(['admin_user']), function (Grid $grid) {
            $grid->tableCollapse(false);
            $grid->rows(function($collection){
                foreach ($collection as $k=>$v){
                    $v->key = $k+1;
                }
                return $collection;
            });

            //$grid->model()->where('user_id', self::user_id());
            $grid->setActionClass(Grid\Displayers\ContextMenuActions::class);

            $grid = $this->gridButton($grid,false);
            $grid->model()->where('user_id', Admin::user()->id);
//            $grid->column('key','排序')->display(function ($q) {
//                return $q .'&nbsp;&nbsp;&nbsp;33333333';
//            });
            $grid->bank_user;
            $grid->usd_amount;
            $grid->del_amount->display(function ($q) {
                return $q .'&nbsp;&nbsp;';
            });
            $grid->rmb_amount_received;
            //$grid->rate;
            $grid->sp_status->using(
                [
                    trans('withdrawal.fields.wclxxxxx'), //未处理::$sp_status[0],
                    trans('withdrawal.fields.bohuxxxx'), //驳回::$sp_status[1],
                    trans('withdrawal.fields.tguoxxxx') //通过::$sp_status[2]
                ]
            )->label(['primary','danger','success'])->display(function ($q) {
                return $q .'&nbsp;&nbsp;&nbsp;';
            });
            $grid->amount_type->using(
                [1=>trans('withdrawal.fields.lcqbxxxx'),2=>trans('withdrawal.fields.yjqbxxxx'), 3=>trans('withdrawal.fields.tzjexxxx')]
            )->label([1=>'success',2=>'primary',3=>'danger']);
            $grid->type->using(
                [1=>trans('withdrawal.fields.bank'),2=>trans('withdrawal.fields.usdt_qb')])->label([1=>'success',2=>'primary']);

            $grid->notes;
            $grid->created_at;

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }


    /***
     *  重构显示页面 用Tab 方式显示多页面
     */
    public function show($id, Content $content)
    {
        return $content
            ->header(trans('withdrawal.labels.Withdrawal'))
            // body 方法可以接受 Laravel 的视图作为参数
            ->row(function (Row $row) use ($id) {
                $row->column(6, function (Column $column) use ($id)  {
                    $column->append($this->detail($id));
                });
            });
    }


    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Withdrawal(), function (Show $show) {
            $show = $this->showButton($show);

            $show->usd_amount;
            $show->rmb_amount_received;
            $show->rate;
            $show->sp_status->using([
                trans('withdrawal.fields.wclxxxxx'), //WithdrawalModel::$sp_status[0],
                trans('withdrawal.fields.bohuxxxx'), //WithdrawalModel::$sp_status[1],
                trans('withdrawal.fields.tguoxxxx') //WithdrawalModel::$sp_status[2]
            ])
            ->dot(['primary','danger','success']);

            $show->amount_type->using(
                [1=>trans('withdrawal.fields.lcqbxxxx'),2=>trans('withdrawal.fields.yjqbxxxx'), 3=>trans('withdrawal.fields.tzjexxxx')]
            )->dot([1=>'success',2=>'primary','danger']);
            if($show->model()->type == 1){
                $show->bank_name;
                $show->bank_number;
                $show->bank_address;
            }else{
                $show->usdt_id;
                $show->usdt_img->image('', '', 100);
            }
            $show->notes;
        });
    }


    /**
     * Create interface.
     *
     * @param Content $content
     *
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->title(trans('admin.menu_titles.投出申请'))
            ->description(' ')
            ->body(function ($row) {
//                $row->column(4, new TotalAdminUsers());
//                $row->column(4, new NewUsers());
//                $row->column(4, new NewDevices());
            })
            ->row(function (Row $row) {

                $row->column(6, function (Column $column){

                    $column->append($this->form());
                });
            });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $rate = config('app.rate');
        $sxf  = config('app.sxf');

        $t1 = Carbon::now()->subWeek(0)->endOfWeek()->toDateString();
        $t2 = Carbon::now()->subWeek(0)->endOfWeek(-1)->toDateString();
        $date = date('Y-m-d');
        $time = date('H');
        $sjbcsbfdsa = trans('withdrawal.fields.sjbcsbfdsa');
        $id3 = $this->getUser()->id;

        Admin::script(
            <<<JS
            // 11111111111111111111111
            var arr = [$t1]
            if ($.inArray($date, arr) == '-1' && $id3 !== 3){
                $('.submit').hide()
                $('button[type=reset]').parent().after("<p style='line-height: 40px;padding-left: 99px;color: #f40000;'>$sjbcsbfdsa</p>");
            }

            $('input[name=usd_amount]').change(function(){
                let rate = "$rate"
                let that = $(this).val()
                let del_amount = that * "$sxf"
                let res = (that - del_amount)
                if (! $('select[name=amount_type]').val()){
                    $(this).val('')
                    layer.msg('请选择申请类型');
                }

                let rmb;
                if ($('select[name=amount_type]').val() == 2){
                    rmb = res * Number(rate)
                }else{
                    rmb = that * Number(rate)
                }

                $('input[name=del_amount]').val(del_amount);
                $('input[name=rmb_amount_received]').val(rmb);
            });
JS
        );

        return Form::make(new Withdrawal(['admin_user']), function (Form $form) {
            $form->title(trans('withdrawal.fields.tjsq'));
            $form = $this->formButton($form);

            $form->select('amount_type',trans('withdrawal.fields.amount_type_2'))
                ->when([2], function (Form $form) {
                    $form->text('del_amount')->required()->disable();
                })->options([
                    1 => trans('withdrawal.fields.lcqbxxxx') .'（'. Admin::user()->trade_balance.'）',
                    2 => trans('withdrawal.fields.yjqbxxxx') .'（'. Admin::user()->agent_balance.'）'
            ])->required();
            $form->text('usd_amount')->required()->rules('required|regex:/^\d+$/', ['regex' => trans('withdrawal.fields.cjjewsz')]);
            $form->text('rmb_amount_received')->required()->type('number')->disable();
            //$form->text('rate')->required();
            $form->text('bank_user')->default(function(){
                return Admin::user()->name;
            })->required();

            $form->radio('type')
                ->when(1, function (Form $form) {
                    $form->text('bank_name')->default(function(){
                        return Admin::user()->bank_type;
                    })->required();
                    $form->text('bank_number')->default(function(){
                        return Admin::user()->bank_number;
                    })->required();
                    $form->text('bank_address')->default(function(){
                        return Admin::user()->bank_address ?? '~';
                    });
                })
                ->when(2, function (Form $form) {
                    $form->text('usdt_id')->default(function(){
                        return Admin::user()->usdt_id;
                    });
                    $form->image('usdt_img')->default(function (){
                        return [Admin::user()->usdt_img];
                    })->disable();
                })->options(['1'=>trans('withdrawal.fields.bank'), '2'=>'USDT'])->default(1);

            $form->textarea('notes')->required();
            $form->hidden('user_id')->default(' ');
            $form->hidden('rmb_del_amount');
            $form->hidden('rate');
            $form->display('created_at')->required();
            $form->display('updated_at');
            $user = $this->getUser();

            $form->saving(function (Form $form) use ($user) {

                return self::setSaving($form, $user);
            });
            $form->saved(function (Form $form) use ($user) {
                if (! $form->getKey()) {
                    return $form->error(trans('withdrawal.fields.sjbcsb'));
                }

                $withdrawal = $form->repository()->eloquent();
                return WithdrawalHandler::deductionUserMoney($withdrawal, '申请投出');
                //return self::setSaved($form, $user, '申请投出');
            });
        });
    }


    /***
     * 保存前 进行数据处理
     * @param $form
     * @param $user
     */
    protected function setSaving($form, $user)
    {
        // 11111111111111111111111
        $t1 = Carbon::now()->subWeek(0)->endOfWeek()->toDateString();
        $t2 = Carbon::now()->subWeek(0)->endOfWeek(-1)->toDateString();

        $id3 = $this->getUser()->id;
        if (!in_array(date('Y-m-d'), [$t1]) && $id3 !== 3){
            return $form->error(trans('withdrawal.fields.sjbcsbfdsa'));
        }

        $rate = config('app.rate');
        $form->user_id = $user->id;
        $form->rate = $rate;

        if (is_null($form->usdt_id) && $form->type == 2){
            return $form->error(trans('withdrawal.fields.zlwrusdt'));
        }
        if (!$user->is_auth){
            return $form->error(trans('withdrawal.fields.zlwrzbkc'));
        }
        if ($user->is_withdrawal != 1){
            return $form->error(trans('withdrawal.fields.bkcjxxxx'));
        }

        switch ($form->amount_type){
            case WithdrawalModel::JIAOYIYUER :
                if ($user->trade_balance < $form->usd_amount ){
                    return $form->error(trans('withdrawal.fields.lcqbxxxx').trans('withdrawal.fields.yebzxxxx'));
                }
                $form->del_amount = 0;
                $form->rmb_del_amount = 0;
                $form->rmb_amount_received = $form->usd_amount * $rate;
                break;
            case WithdrawalModel::DAILIYUER :
                if ($user->agent_balance < $form->usd_amount ){
                    return $form->error(trans('withdrawal.fields.yjqbxxxx').trans('withdrawal.fields.yebzxxxx'));
                }
                $del_amount = $form->usd_amount * config('app.sxf');
                $form->del_amount = $del_amount;
                $form->rmb_del_amount = $del_amount * $rate;
                $form->rmb_amount_received = ($form->usd_amount - $del_amount) * $rate;

                break;
            default:
                return $form->error(trans('withdrawal.fields.csywxxxx'));
        }

        // 中断后续逻辑
        //return $form->error($form->del_amount);
    }









}
